<template>
  <div class="template-container">
    <!-- 顶部标题和操作区 -->
    <el-card class="header-card">
      <div class="header-content">
        <h2>视频模板管理</h2>
        <div class="actions">
          <el-button type="primary" @click="handleSync" :loading="templateStore.syncLoading">
            <el-icon><RefreshRight /></el-icon>同步模板
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="templateQuery" ref="queryForm" :inline="true">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateQuery.name" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模板列表 -->
    <el-card v-loading="templateStore.loading">
      <div class="template-list" v-if="templateStore.templates.length > 0">
        <div class="template-card"
             v-for="template in templateStore.templates"
             :key="template.id"
             @click="handleTemplateSelect(template)">
          <div class="template-thumbnail">
            <el-image
                :src="template.thumbnailUrl"
                fit="cover"
                :preview-src-list="[template.thumbnailUrl]">
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <div class="template-info">
            <h4>{{ template.name || '未命名模板' }}</h4>
            <p>最近更新: {{ formatDate(template.lastSyncTime) }}</p>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无模板数据" />

      <!-- 分页 -->
      <div class="pagination" v-if="templateStore.total > 0">
        <el-pagination
            v-model:current-page="templateQuery.pageNum"
            v-model:page-size="templateQuery.pageSize"
            :total="templateStore.total"
            :page-sizes="[8, 12, 24, 36]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 生成视频弹窗 -->
    <el-dialog
        v-model="generateDialog.visible"
        title="生成视频"
        width="700px"
        top="5vh"
        :close-on-click-modal="false"
        :destroy-on-close="true"
    >
      <!-- 对话框内容和表单部分保持不变 -->

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="generateDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleGenerateVideo" :loading="templateStore.generating">
            生成视频
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 视频状态弹窗 -->
    <el-dialog
        v-model="statusDialog.visible"
        title="视频生成状态"
        width="600px"
        :close-on-click-modal="false"
    >
      <!-- 状态对话框内容保持不变 -->
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import {
  RefreshRight, Search, Refresh, Picture,
  Download, Microphone, VideoCamera, Upload
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useTemplateStore } from '@/stores/template'

// 使用Pinia Store
const templateStore = useTemplateStore()

// 查询参数
const templateQuery = reactive({
  name: '',
  pageNum: 1,
  pageSize: 12
})

// 生成对话框
const generateDialog = reactive({
  visible: false
})

// 状态对话框
const statusDialog = reactive({
  visible: false
})

// 视频生成表单
const generateForm = reactive({
  templateId: '',
  configId: '',
  variables: {},
  config: {
    title: '新视频',
    caption: false,
    test: false,
    dimension: {
      width: 1080,
      height: 1920
    }
  }
})

// 表单引用
const generateFormRef = ref(null)

// 校验规则
const rules = {
  configId: [
    { required: true, message: '请选择配置', trigger: 'change' }
  ]
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知时间'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取模板列表
const fetchTemplates = () => {
  templateStore.fetchTemplates(templateQuery)
}

// 同步模板
const handleSync = async () => {
  try {
    await templateStore.syncTemplates()
    fetchTemplates()
  } catch (error) {
    // 错误已在store中处理
  }
}

// 查询按钮
const handleQuery = () => {
  templateQuery.pageNum = 1
  fetchTemplates()
}

// 重置按钮
const resetQuery = () => {
  templateQuery.name = ''
  templateQuery.pageNum = 1
  fetchTemplates()
}

// 分页方法
const handleSizeChange = (val) => {
  templateQuery.pageSize = val
  fetchTemplates()
}

const handleCurrentChange = (val) => {
  templateQuery.pageNum = val
  fetchTemplates()
}

// 选择模板
const handleTemplateSelect = async (template) => {
  generateForm.templateId = template.id

  const result = await templateStore.selectTemplate(template)

  if (result.success) {
    // 初始化变量
    generateForm.variables = {}
    Object.entries(templateStore.templateVariables).forEach(([key, variable]) => {
      generateForm.variables[key] = {
        name: variable.name,
        type: variable.type,
        properties: { ...variable.properties }
      }
    })

    generateDialog.visible = true
  }
}

// 配置变化处理
const handleConfigChange = (configId) => {
  if (!configId) return

  const selectedConfig = templateStore.configList.find(config => config.id === configId)
  if (selectedConfig) {
    // 更新视频尺寸
    generateForm.config.dimension = {
      width: selectedConfig.width,
      height: selectedConfig.height
    }

    // 更新字幕设置
    generateForm.config.caption = selectedConfig.isCaption

    // 如果有角色变量，尝试更新角色ID
    Object.entries(generateForm.variables).forEach(([key, variable]) => {
      if (variable.type === 'character' && selectedConfig.avatarId) {
        variable.properties.character_id = selectedConfig.avatarId
      }

      // 如果有语音变量，尝试更新语音ID
      if (variable.type === 'voice' && selectedConfig.voiceId) {
        variable.properties.voice_id = selectedConfig.voiceId
      }
    })
  }
}

// 生成视频
const handleGenerateVideo = async () => {
  try {
    if (generateFormRef.value) {
      await generateFormRef.value.validate()
    }

    const payload = {
      templateId: templateStore.selectedTemplate.templateId,
      configId: generateForm.configId,
      variables: generateForm.variables,
      config: generateForm.config
    }

    const result = await templateStore.generateVideo(payload)

    if (result.success) {
      generateDialog.visible = false
      statusDialog.visible = true
    }
  } catch (error) {
    // 错误已在store中处理
  }
}

// 下载视频
const handleDownloadVideo = () => {
  if (!templateStore.videoRecord.videoUrl) {
    ElMessage.warning('视频URL不存在')
    return
  }

  // 创建一个隐藏的a标签并模拟点击
  const link = document.createElement('a')
  link.href = templateStore.videoRecord.videoUrl
  link.download = `video_${Date.now()}.mp4`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 组件挂载时执行
onMounted(() => {
  fetchTemplates()
})

// 组件销毁前清理
onBeforeUnmount(() => {
  // 清除状态检查定时器
  if (templateStore.statusCheckTimer) {
    clearInterval(templateStore.statusCheckTimer)
  }
})
</script>

<style scoped>
.template-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card {
  margin-bottom: 20px;
}

.template-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.template-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.template-thumbnail {
  height: auto;
  overflow: hidden;
}

.template-thumbnail .el-image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.template-info {
  padding: 10px;
}

.template-info h4 {
  margin: 0 0 5px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.template-info p {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.template-preview {
  text-align: center;
  margin-bottom: 20px;
}

.template-preview .el-image {
  max-height: 200px;
  max-width: 100%;
}

.preview-info {
  margin-top: 10px;
}

.preview-info h3 {
  margin: 0;
  font-size: 18px;
}

.config-option {
  display: flex;
  align-items: center;
}

.config-avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.config-info {
  display: flex;
  flex-direction: column;
}

.config-info small {
  color: #909399;
}

.avatar-option {
  display: flex;
  align-items: center;
}

.avatar-preview-small {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.voice-option {
  display: flex;
  align-items: center;
}

.voice-option .el-icon {
  margin-right: 10px;
  color: #409EFF;
}

.media-variable {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
}

.current-media {
  text-align: center;
}

.media-preview {
  max-height: 150px;
  overflow: hidden;
  margin-bottom: 10px;
}

.media-info {
  margin: 5px 0;
  color: #606266;
}

.no-media {
  color: #909399;
  padding: 20px;
}

.status-container {
  padding: 20px 0;
}

.status-info {
  margin-top: 30px;
}

.status-text {
  margin-bottom: 20px;
}

.video-result {
  margin-top: 20px;
}

.video-preview {
  margin-bottom: 15px;
}

.preview-video {
  width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.video-actions {
  text-align: center;
}
</style>